import { PrismaClient, Prisma } from "@prisma/client";
import { PrismaSqlUtils } from "../utils/prisma.sql.utils";
import { TransferDateFormatter } from "../utils/tranferDateFormatter";

const prisma = new PrismaClient({ log: ["query", "error", "info", "warn"] });
const prismaSqlUtils = new PrismaSqlUtils();
export class BlogService {
  async getAllBlogs(
    page: number,
    pageSize: number,
    search: string
  ): Promise<any | null> {
    const offset = pageSize * (page - 1);
    const limit = pageSize;
    let selectSql = "SELECT b.*, u.username ";
    let clauseSql = ` FROM blog b \
                        JOIN user u ON b.user_id = u.id \
                        WHERE b.status = 'published' \
                        `;
    // search 不能为null,或者""
    if (this.notEmpty(search)) {
      clauseSql += ` AND b.title LIKE ? `;
    }
    clauseSql += " Order By b.created_at DESC ";
    let limitSql = "LIMIT  ? , ? ";
    let statSql = selectSql + clauseSql + limitSql;
    let countSql = "SELECT COUNT(*) as total " + clauseSql;
    let blogs = null;
    let total = null;
    console.log("search:" + search);
    console.log("offset:" + offset);
    console.log("limit:" + limit);
    if (this.notEmpty(search)) {
      search = "%" + search + "%";
      blogs = await prismaSqlUtils.queryMany(statSql, search, offset, limit);
      total = await prismaSqlUtils.queryOne(countSql, search);
    } else {
      blogs = await prismaSqlUtils.queryMany(statSql, offset, limit);
      total = await prismaSqlUtils.queryOne(countSql);
    }
    TransferDateFormatter.transferDate(blogs);
    return { blogs, total: parseInt(total.total.toString()) as number };
  }
  notEmpty(search: string) {
    return search !== null && search !== undefined && search.trim() !== "";
  }

  async getBlogById(id: number): Promise<any | null> {
    const blog = await prisma.blog.findUnique({
      where: { id: Number(id) },
    });
    TransferDateFormatter.transferDate(blog);
    return blog;
  }
  async createBlog(data: Prisma.blogCreateInput): Promise<any> {
    return await prisma.blog.create({
      data,
    });
  }
  async updateBlog(id: number, data: Prisma.blogUpdateInput): Promise<any> {
    return await prisma.blog.update({
      where: { id },
      data,
    });
  }
  async deleteBlog(id: number): Promise<any> {
    return await prisma.blog.delete({
      where: { id },
    });
  }
  async getBlogByAuthorId(
    userId: number,
    page: number,
    pageSize: number
  ): Promise<any> {
    const blogs = await prisma.blog.findMany({
      where: { user_id: userId },
      skip: (page - 1) * pageSize,
      take: pageSize,
    });
    const total = await prisma.blog.count({
      where: { user_id: userId },
    });
    TransferDateFormatter.transferDate(blogs);
    return { blogs, total };
  }
}
